package home;

/**
 * Created by clq on 2019/4/16.
 */
public class Merge {
    static Comparable aux[] = null;
    public static void main(String[] args) {
        Comparable arr[] = {123,2,12,234,2,12,2342,12,0,1};
        aux = new Comparable[arr.length];
        sort(arr);
        for(Comparable cmp:arr) {
            System.out.println(cmp);
        }
    }
    public static void sort(Comparable []arr) {
        sort(arr, 0, arr.length-1);
    }

    public static void sort(Comparable [] arr, int lo, int hi) {
        if(lo>=hi) {
            return;
        }
        int mid = lo+(hi-lo)/2;
        sort(arr, lo, mid);
        sort(arr, mid+1, hi);
        merge(arr, lo, mid, hi);
    }

    public static void merge(Comparable []arr, int lo, int mid, int hi) {
        int i=lo; int j=mid+1;
        for(int k=lo; k<=hi; k++) {
            aux[k] = arr[k];
        }
        for(int k=lo; k<=hi; k++) {
            if(i>mid) arr[k] = aux[j++];
            else if(j>hi) arr[k] = aux[i++];
            else if(less(aux[j], aux[i])) {arr[k] = aux[j++];}
            else arr[k] = aux[i++];
        }
    }

    public static boolean less(Comparable a, Comparable b) {
        return a.compareTo(b)<0 ? true:false;
    }
}
